const { Router } = require('express')
const router = new Router()

// 引入用户信息表
const UserInformationModel = require('../../model/userImformation')

function oprater(request,response){
    const { _id, addressId, name, tel, areaCode, addressDetail, province, city, county, postalCode, isDefault } = request.query
    UserInformationModel.findOneAndUpdate({
        _id,
        addressArr: {
            $elemMatch: {
                _id: addressId
            }
        }
    },{
        $set:{
            'addressArr.$.name': name,
            'addressArr.$.addressDetail': addressDetail,
            'addressArr.$.tel': tel,
            'addressArr.$.areaCode': areaCode,
            'addressArr.$.province': province,
            'addressArr.$.city': city,
            'addressArr.$.county': county,
            'addressArr.$.postalCode': postalCode,
            'addressArr.$.isDefault': isDefault
        }
    },function (err,doc) {
        const data = {
            code: '200'
        }
        if (err){
            data.msg = '修改地址失败'
            data.data = 'error'
        } else {
            data.msg = '修改地址成功'
            data.data = 'success'
        }
        return response.json(data)
    })
}

router.get('/updateAddress',(request, response)=>{
    const { _id, isDefault } = request.query

    // 如果是修改地址改为了默认地址，那就要把之前的默认地址改掉，在对子文档进行操作
    // 因为传递过来的isDefault是字符串类型，防止它又变成bol类型所以加了一个 ||
    if(isDefault == 'true' || isDefault == true){
        UserInformationModel.updateOne({
            _id,
            addressArr: {
                $elemMatch: {
                    isDefault: true
                }
            }
        },{
            $set:{
                // 这一步是这样子写是固定的，不然无法保留原有数据
                "addressArr.$.isDefault": false
            }
        },function (err,doc) {
            let data = {
                code: '200'
            }
            if (err){
                data.msg = '修改默认地址失败'
                data.data = 'error'
                return response.json(data)
            } else {
                oprater(request,response)
            }
        })
    }else {
        oprater(request,response)
    }

})

router.get('/deleteAddress',(request, response)=>{
    const { _id, addressId } = request.query

    UserInformationModel.updateOne({
        _id,
        addressArr:{
            $elemMatch: {
                _id: addressId
            }
        }
    },{
        $pull:{
            addressArr:{
                _id: addressId
            }
        }
    },function (err, doc) {
        const data = {
            code: '200'
        }
        if (err) {
            data.msg = '删除地址失败'
            data.data = 'error'
            console.log('======')
            console.log(err)
        }else {
            data.msg = '删除地址成功'
            data.data = 'success'
        }
        response.json(data)
    })
})

module.exports = router
